package com.example.blog.common.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class Md5Utils {
    /**
     * md5 加密
     */
    public static String encrypt(String password){
        String salt = UUID.randomUUID().toString().replace("-","");
        //md5(盐值+明文）
        String secretPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));

        //数据存储的是：盐值+密文
        return salt+secretPassword;
    }

    /**
     * 验证
     * true-密码正确，false-密码错误
     */
    public static Boolean verify(String inputPassword,String sqlPassword){
        if (!StringUtils.hasLength(inputPassword) || !StringUtils.hasLength(sqlPassword)){
            return false;
        }

        if (sqlPassword.length()!=64){
            return false;
        }

        String salt = sqlPassword.substring(0,32);
        String secretPassword = DigestUtils.md5DigestAsHex((salt+inputPassword).getBytes(StandardCharsets.UTF_8));

        return sqlPassword.equals(salt+secretPassword);

    }
}

























